import React, {Component, PropTypes} from 'react';
import moment from 'moment';

import { Table, Popconfirm, message, Button, Icon, Modal, Form, Input, DatePicker, InputNumber, TimePicker,Row,Col  } from 'antd';

const FormItem = Form.Item;
const createForm = Form.create;

const dateFormat = 'YYYY-MM-DD';
const timeFormat = 'HH:mm';

class FormComponent extends Component {

  state = {
    formVisible: this.props.formVisible
  }

  constructor (props) {
    super(props);
  }

  /**
   * 弹层点击取消操作
   */
  handleFormCancel () {
    this.props.handleHide();
  }

  componentWillReceiveProps (props) {

    // console.log(props);

    if(this.state.formVisible != props.formVisible){
      this.setState({
        formVisible : props.formVisible
      });
      props.formVisible === false && this.props.form.resetFields();
    }
  }

  /**
   * 弹层点击确定操作
   */
  handleFormOk () {
    this.props.form.validateFields((err, values) => {
      if(!err){
        let fields = this.props.form.getFieldsValue();

        if(fields.room_start_time >= fields.room_end_time){
          message.error('结束时间不能小于开始时间');
          return false;
        }

        if(this.props.formValues && this.props.formValues.$loki){
          fields.$loki = this.props.formValues.$loki;
        }
        this.props.handleOK(fields);
      }
    });
  }

  disabledDate (current) {
    // const exam_range = this.props.examdetail.exam_range;
    // const start = moment(exam_range[0]), end = moment(exam_range[1]).add(1,'day');

    const start = moment(this.props.examdetail.exam_start_date), end = moment(this.props.examdetail.exam_end_date).add(1,'day');
    return current && (current.valueOf() < start || current.valueOf() > end);
  }

  disabledHours() {
    return [0,1,2,3,4,5,6,7,21,22,23,24];
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const title = this.props.formType === 'add' ? '添加考场' : '编辑考场';

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 14 },
      },
    };

    return (
      <div>
        <Modal title={title}
               visible={this.state.formVisible}
               onOk={this.handleFormOk.bind(this)}
               onCancel={this.handleFormCancel.bind(this)}>

          <Form>

            <FormItem
              {...formItemLayout}
              label="考场名称"
              hasFeedback
            >
              {getFieldDecorator('room_name', {
                rules: [{ required: true, message: '考场名称不能为空!' }],
              })(
                <Input placeholder="请填写考场名称" />
              )}
            </FormItem>

            <FormItem
              {...formItemLayout}
              label="考试日期"
              hasFeedback
            >
              {getFieldDecorator('room_date', {
                rules: [{ required: true, message: '考场时间不能为空!' }],
              })(
                <DatePicker disabledDate={this.disabledDate.bind(this)} />
              )}
            </FormItem>

            <Row>
              <Col {...formItemLayout.labelCol} className="ant-form-item-label"><label className="ant-form-item-required">考试时间</label></Col>
              <Col {...formItemLayout.wrapperCol}>
                <Row>
                  <Col span={11}>
                    <FormItem
                      hasFeedback
                    >
                      {getFieldDecorator('room_start_time', {
                        rules: [{ required: true, message: '开始时间不能为空!' }]
                      })(
                        <TimePicker placeholder="开始时间" format={timeFormat} disabledHours={this.disabledHours.bind(this)} />
                      )}
                    </FormItem>
                  </Col>
                  <Col span={2} className="ant-form-x" style={{'text-align':'left'}}>-</Col>
                  <Col span={11}>
                    <FormItem
                      hasFeedback
                    >
                      {getFieldDecorator('room_end_time', {
                        rules: [{ required: true, message: '结束时间不能为空!' }]
                      })(
                        <TimePicker placeholder="结束时间" format={timeFormat} disabledHours={this.disabledHours.bind(this)} />
                      )}
                    </FormItem>
                  </Col>
                </Row>
              </Col>
            </Row>

            <FormItem
              {...formItemLayout}
              label="容纳人数"
              hasFeedback
            >
              {getFieldDecorator('room_number', {
                rules: [{ required: true, message: '容纳人数不能为空!' }],
              })(
                <InputNumber placeholder="容纳人数" />
              )}
            </FormItem>

            <FormItem
              {...formItemLayout}
              label="监考教师"
              hasFeedback
            >
              {getFieldDecorator('room_teacher', {
                rules: [],
              })(
                <Input />
              )}
            </FormItem>

          </Form>

        </Modal>
      </div>
    )
  }

}

const formatObj = function (obj) {
  var ret = {};
  for(var i in obj){
    ret[i] = {
      value : obj[i]
    }
  }
  return ret;
}
const RoomForm =  createForm({
  mapPropsToFields(props) {
    return formatObj(props.formValues)
  }
})(FormComponent);

export default class Step1 extends Component {

  state = {
    index : null,
    formType : 'add',
    formValues : null,
    formVisible : false
  }

  constructor (props) {
    super(props);

    /**
     * table头部
     * @type {*[]}
     */
    this.columns = [{
      title: '考场名称',
      width: 150,
      dataIndex: 'room_name'
    }, {
      title: '考试日期',
      width: 150,
      dataIndex: 'room_date'
    },{
      title: '考试时间',
      width: 150,
      render : (text,record) => {
        return (
          <spa>{record.room_start_time} ~ {record.room_end_time}</spa>
        )
      }
    },{
      title: '容纳人数',
      width: 80,
      dataIndex: 'room_number'
    },{
      title: '监考教师',
      dataIndex: 'room_teacher'
    }, {
      title : '操作',
      width: 100,
      render: (text,record,index) => {
        return (
          <span>
            <a href="JavaScript:;" onClick={this.handleRoomEdit.bind(this,record,index)}>编辑</a>
            <span className="ant-divider" />
            <Popconfirm title="确定删除本场考场么?" onConfirm={this.handleRoomDelete.bind(this,record,index)} >
              <a href="#">删除</a>
            </Popconfirm>
          </span>
        )
      },
    }];
  }

  // componentWillReceiveProps (props) {
  //   if(this.props.$loki != props.$loki){
  //     this.getExamDetail({
  //       exam_id : props.$loki
  //     });
  //   }
  // }

  componentDidMount () {
    this.getRoomList({
      exam_id : this.props.$loki
    });
  }

  /**
   * 获取考场列表
   */
  getRoomList (formdata = {}) {
    const { appActions, examActions } =  this.props;
    appActions.loading(true).then(()=>{
      return examActions.getRoomList(formdata)
    }).then(()=>{
      appActions.loading(false);
    }).catch(err=>{
      message.error(err.msg);
    })
  }

  /**
   * 添加考场
   * @param e
   */
  handleRoomAdd (e) {
    this.setState({
      formType : 'add',
      formValues : null,
      formVisible : true
    })
  }

  /**
   * 隐藏modal弹出层
   */
  handleHideModal () {
    this.setState({
      formValues : null,
      formVisible:false
    })
  }

  /**
   * 考场提交
   * @param formdata
   */
  handleRoomSubmit (data) {
    const {examActions} = this.props;
    let formdata = data;
    formdata.exam_id = this.props.$loki;
    formdata['room_date'] = formdata['room_date'].format(dateFormat);
    formdata['room_start_time'] = formdata['room_start_time'].format(timeFormat);
    formdata['room_end_time'] = formdata['room_end_time'].format(timeFormat);

    if(formdata.$loki){
      formdata.index = this.state.index;
      examActions.postEditRoom(formdata).then(data=>{
        this.handleHideModal();
      }).catch(err=>{
        typeof err.msg == 'object' ?
          message.error(err.msg.message) :
          message.error(err.msg);
      });
    }else{
      examActions.postAddRoom(formdata).then(data=>{
        this.handleHideModal();
      }).catch(err=>{
        message.error(err.msg);
      });
    }
  }

  handleFormOk () {
    const {exam} = this.props;
    const list = exam.get('roomlist') && exam.get('roomlist').toArray();
    if(!list || list.length < 1){
      message.error('请添加考场');
      return false;
    }
    this.props.next()
  }

  /**
   * 编辑考场信息
   * @param formValues
   * @param index
   */
  handleRoomEdit (data,index) {
    let formValues = Object.assign({},data);
    formValues['room_date'] = moment(formValues['room_date'],dateFormat);
    formValues['room_start_time'] = moment(formValues['room_start_time'],timeFormat);
    formValues['room_end_time'] = moment(formValues['room_end_time'],timeFormat);

    this.setState({
      index,
      formType : 'edit',
      formVisible:true,
      formValues
    })
  }


  /**
   * 操作删除考场
   * @param $loki
   */
  handleRoomDelete (formdata,index) {
    this.props.examActions.postDeleteRoom({
      index,
      $loki : formdata.$loki,
      exam_id : this.props.$loki
    }).then(data=>{
      message.success('删除成功');
    }).catch(err=>{
      message.error(err.msg);
    })
  }

  render() {

    const {exam} = this.props;
    const list = exam.get('roomlist') && exam.get('roomlist').toArray();
    const examdetail = exam && exam.get('examdetail').toJS();

    console.log(list);

    return (
      <div className="ant-steps-wraper">

        <div className="steps-content">
          <div className="clearfix">
            <Button className="ant-room-add" type="primary" onClick={this.handleRoomAdd.bind(this)}>
              <Icon type="folder-add" />添加考场
            </Button>
            <h3>考场列表:</h3>
          </div>
          <Table
            className="ant-room-table"
            bordered
            columns={this.columns}
            dataSource={list}
            pagination={false}
          />
        </div>
        <div className="steps-action">
          <Button type="primary" className="ant-next-btn" onClick={() => this.handleFormOk()}>下一步</Button>
          <Button className="ant-previous-btn" onClick={() => this.props.prev()}>
            返回上一步
          </Button>
        </div>

        <RoomForm
          examdetail={examdetail}
          formType={this.state.formType}
          formValues={this.state.formValues}
          formVisible={this.state.formVisible}
          handleHide={this.handleHideModal.bind(this)}
          handleOK={this.handleRoomSubmit.bind(this)}
        />

      </div>
    )
  }

}
